// import { preferences } from '@vben/preferences';

import type { AxiosInstance } from 'axios';

import { useAccessStore } from '@vben/stores';

import axios from 'axios';

import { createFileUpload, createShareCollection } from '../file-transfer';
import { ShareItemControllerApiExtended as ShareItemControllerApi } from '../file-transfer/download-link';
import {
  AvatarControllerApi,
  Configuration,
  ConnectionControllerApi,
  FileControllerApi,
  FilePreviewControllerApi,
  MessageControllerApi,
  StatControllerApi,
  StatisticControllerApi,
  UserControllerApi,
} from '../openapi';
import { tokenManager } from './token-manager';

const basePath =
  import.meta.env.VITE_API_BASE_URL || 'http://139.196.172.73:8081';
const axiosInstance = axios.create({
  timeout: 10_000,
}) as AxiosInstance;

// Token刷新状态管理
let refreshTokenQueue: Array<(token: string) => void> = [];

// 添加请求拦截器
axiosInstance.interceptors.request.use(
  async (config) => {
    const accessStore = useAccessStore();

    // 添加Authorization头
    if (accessStore.accessToken) {
      // 检查并刷新即将过期的token
      const currentToken = await tokenManager.checkAndRefreshToken();
      if (currentToken) {
        config.headers.Authorization = `Bearer ${currentToken}`;
      }
    }

    return config;
  },
  (error) => {
    return Promise.reject(error);
  },
);

// 添加响应拦截器
axiosInstance.interceptors.response.use(
  (response) => {
    return response;
  },
  async (error) => {
    const { config, response } = error;

    // 处理401认证错误
    if (response?.status === 401) {
      const accessStore = useAccessStore();

      // 如果没有refreshToken或者已经是重试请求，直接跳转登录
      if (!accessStore.refreshToken || config._retry) {
        accessStore.setAccessToken(null);
        accessStore.setRefreshToken(null);
        tokenManager.stopAutoRefresh();

        // 重定向到登录页面
        if (typeof window !== 'undefined') {
          window.location.href = '/login';
        }
        throw error;
      }

      try {
        // 使用TokenManager刷新token
        const newToken = await tokenManager.refreshToken();

        // 处理队列中的请求
        refreshTokenQueue.forEach((callback) => callback(newToken));
        refreshTokenQueue = [];

        // 重试原始请求
        config.headers.Authorization = `Bearer ${newToken}`;
        config._retry = true;
        return axiosInstance.request(config);
      } catch (refreshError) {
        // 刷新失败，清除token并跳转登录
        refreshTokenQueue = [];
        accessStore.setAccessToken(null);
        accessStore.setRefreshToken(null);
        tokenManager.stopAutoRefresh();

        if (typeof window !== 'undefined') {
          window.location.href = '/login';
        }
        throw refreshError;
      }
    }

    throw error;
  },
);

const config = new Configuration({
  basePath,
});
export const client = {
  connection: new ConnectionControllerApi(config, basePath, axiosInstance),
  user: new UserControllerApi(config, basePath, axiosInstance),
  avatar: new AvatarControllerApi(config, basePath, axiosInstance),
  file: new FileControllerApi(config, basePath, axiosInstance),
  filePreview: new FilePreviewControllerApi(config, basePath, axiosInstance),
  shareItem: new ShareItemControllerApi(config, basePath, axiosInstance),
  statistic: new StatisticControllerApi(config, basePath, axiosInstance),
  message: new MessageControllerApi(config, basePath, axiosInstance),
  stat: new StatControllerApi(config, basePath, axiosInstance),
};

// 文件传输相关的便捷方法
export const fileTransfer = {
  /**
   * 创建文件上传实例
   */
  createUpload: (chunkSize?: number) =>
    createFileUpload(client.file, chunkSize),

  /**
   * 创建分享集合实例
   */
  createShareCollection: (chunkSize?: number) =>
    createShareCollection(client.file, chunkSize),
};
